<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item style="font-weight: bolder;">菜品管理</el-breadcrumb-item>
      <el-breadcrumb-item>菜品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:20px ;">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="#" type="index">
        </el-table-column>
        <el-table-column label="图片" width="150">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.imageUrl">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="菜品" width="120" sortable>
        </el-table-column>
        <el-table-column prop="type" label="菜品类目" width="120" sortable>
        </el-table-column>
        <el-table-column prop="desc" label="简介">
        </el-table-column>
        <el-table-column prop="price" label="单价" width="120" sortable>
        </el-table-column>
        <el-table-column prop="recommend" label="推荐菜品" width="120">
        </el-table-column>
        <el-table-column prop="createdAt" label="时间" sortable>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <!-- 上架/下架按钮 -->
            <el-button type="success" icon="el-icon-d-caret" size="mini" @click="showPutawaySlodout(scope.row)">{{scope.row.state}}</el-button>
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)" :disabled="isTrue">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeFoodById(scope.row.id)" :disabled="isTrue">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block" style="margin-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
          :total="total"></el-pagination>
      </div>
      <!-- 修改对话框 -->
      <el-dialog title="菜品修改" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="菜品" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="单价" prop="price">
            <el-input v-model="ruleForm.price" oninput="value=value.replace(/[^\d.]/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="菜品状态" prop="state">
            <el-radio-group v-model="ruleForm.state">
              <el-radio label="上架"></el-radio>
              <el-radio label="下架"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜品类目" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择菜品类目">
              <el-option :label="item.leimu" :value="item.leimu" v-for="item in allType" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 是否为商家推荐菜品 -->
          <el-form-item label="推荐菜品" prop="recommend">
            <el-radio-group v-model="ruleForm.recommend">
              <el-radio label="是"></el-radio>
              <el-radio label="否"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 推荐菜品的三个标签 -->
          <el-form-item label="菜品标签一" prop="tag_1">
            <el-input v-model="ruleForm.tag_1"></el-input>
          </el-form-item>
          <el-form-item label="菜品标签二" prop="tag_2">
            <el-input v-model="ruleForm.tag_2"></el-input>
          </el-form-item>
          <el-form-item label="菜品标签三" prop="tag_3">
            <el-input v-model="ruleForm.tag_3"></el-input>
          </el-form-item>
          <!-- 上传图片 -->
          <el-form-item label="图片">
            <el-upload action="/ordering/food/upload" list-type="picture-card" :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove" :on-success="afterSuccessUpload"  ref="upload">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFood()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import jwtDecode from 'jwt-decode'
  export default {
    data() {
      // 自定义函数，每个if、else都要添加callback()
      var recommend = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('是否为商家推荐菜品'));
        } else {
          callback();
        }
      }
      // 检验是否为推荐菜品，如果是推荐菜品，则一定要填写标签
      var isRecommend = (rule, value, callback) => {
        if (this.ruleForm.recommend === '是') {
          if (value === '') {
            callback(new Error('请填写3个推荐菜品标签！'));
          } else if (value.length > 4) {
            callback(new Error('推荐菜品标签字数限定为1-4！'));
          }else {
            callback();
          }
        } else {
          callback();
        }
      }
      return {
        isTrue: false,
        // 这个用来记录菜品类目
        allType: [],
        // 上传图片
        dialogImageUrl: '',
        // 控制图片展示框
        dialogVisible: false,
        // 这个用来存储获取过来的菜品的信息
        ruleForm: {
          name: '',
          price: '',
          desc: '',
          type: '',
          state: '',
          imageUrl: '',
          recommend: '',
          tag_1: '',
          tag_2: '',
          tag_3: ''
        },
        editDialogVisible: false,
        // 菜品列表数据
        tableData: [],
        // 获取菜品列表的参数
        queryInfo: {
          // 关键字
          query: '',
          // 当前的页数
          pagenum: 1,
          // 当前每页显示多少条数据
          pagesize: 5
        },
        // 列表总数
        total: 0,
        // 表单字段的验证规则
        rules: {
          name: [{
              required: true,
              message: '请输入菜品名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 7,
              message: '菜品名字数在 1 到 6 个字符',
              trigger: 'blur'
            }
          ],
          price: [{
            required: true,
            message: '单价不能为空',
            trigger: 'blur'
          }],
          desc: [{
            required: true,
            message: '简介不能为空',
            trigger: 'blur'
          }, {
            min: 5,
            max: 30,
            message: '菜品简介字数在 5 到 30 个字符',
            trigger: 'blur'
          }],
          state: [{
            required: true,
            message: '请选择菜品状态',
            trigger: 'change'
          }],
          type: [{
            required: true,
            message: '请选择菜品类目',
            trigger: 'change'
          }],
          recommend: [{
            validator: recommend,
            trigger: 'change'
          }],
          tag_1: [{
            validator: isRecommend,
            trigger: 'blur'
          }],
          tag_2: [{
            validator: isRecommend,
            trigger: 'blur'
          }],
          tag_3: [{
            validator: isRecommend,
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getFoodList()
      const tokenStr = window.sessionStorage.getItem('token')
      const decode = jwtDecode(tokenStr)
      if (decode.scope !== '超级管理员') {
        this.isTrue = true
      }
    },
    methods: {
      // 重置表单
      resetForm() {
        this.$refs.ruleFormRef.resetFields();
        // 清空上传图片列表
        this.$refs.upload.clearFiles()
      },
      // 提交修改后的菜品信息
      editFood() {
        this.$refs.ruleFormRef.validate(async (valid) => {
          if (valid) {
            const foodResult = await this.$http.put('/ordering/food', this.ruleForm)
            console.log(foodResult)
            if (foodResult.status !== 200) {
              this.$message.error('修改菜品失败')
            }
            this.$message.success('修改菜品成功')
            this.getFoodList()
            this.editDialogVisible = false
            this.resetForm()
          } else {
            return false;
          }
        })
      },
      // 获取菜品类目
      async getType() {
        const allType = await this.$http.get('/ordering/getType')
        if (allType.status !== 200) {
          return this.$message.error('获取菜品类目失败')
        }
        this.allType = allType.data.allType
      },
      // 移除图片
      handleRemove(file, fileList) {},
      // 上传图片前预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 上传图片成功后
      afterSuccessUpload(file) {
        this.ruleForm.imageUrl = file.filename
      },
      // 点击修改，显示修改对话框
      async showEditDialog(id) {
        const food = await this.$http.get(`/ordering/getFood/${id}`)
        if (food.status !== 200) {
          this.$message.error('获取菜品失败！')
        }
        this.ruleForm = food.data
        this.editDialogVisible = true
        this.getType()
      },
      // 删除菜品
      async removeFoodById(id) {
        // 弹框提示轮播图是否删除
        const confirmResult = await this.$confirm(
          '此操作将永久删除这菜品, 是否继续?',
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err)
        // 如果用户确定了  返回confirm     如果用户取消了 返回cancel
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除！')
        }
        const u = await this.$http.delete(`ordering/food/${id}`)
        if (u.status !== 200) {
          this.$message.error('删除菜品失败！')
        }
        this.getFoodList()
        this.$message.success('删除菜品成功！')
      },
      // 菜品上架/下架
      async showPutawaySlodout(row) {
        const state = await this.$http.put('/ordering/foodState', row)
        if (state.status !== 200) {
          return this.$message.error('更改菜品状态失败')
        }
        this.getFoodList()
        this.$message.success('更改菜品状态成功')
      },
      // 获取列表数据
      async getFoodList() {
        const u = await this.$http.get('/ordering/foods', {
          params: this.queryInfo
        })
        if (u.status !== 200) {
          return this.$message.error('获取菜品列表失败！')
        }
        this.tableData = u.data.foodList
        this.total = u.data.total
        // this.$message.success('获取菜品列表成功')
      },
      // 监听改变每页显示多少条数据
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getFoodList()
      },
      // 监听改变当前页码
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getFoodList()
      }
    }
  }
</script>

<style>
</style>
